<script>
  import SCharacterCard from '@/sheep/components/s-character-card/s-character-card.vue';
  import sheep from '@/sheep';

  export default {
    name: 'RecursiveList',
    data() {
      return {
        generationList: [],
        generationListWidth: [],
        queryIndex: [],
        listWidth: 0,
        // 当前组件的高度
        rectHeight: 0,
      };
    },
    props: {
      children: {
        type: Array,
        default: () => {
          return [];
        },
      },
      isTopLevel: {
        type: Boolean,
        default: false,
      },
      is_init: 0,
      is_create: 0,
      generation: 0,
      show_die_gray: 0,
      id: 0,
      centerId: 0,
      endId: 0,
      is_simple: 0,
      is_first: false,
      genealogicalHead: {
        type: Object,
        default: () => {
          return {};
        },
      },
      zibei_List: {
        type: Array,
        default: () => {
          return [];
        },
      },
      listHeight: {
        type: Number,
        default: 0,
      },
      showBackground: {
        type: Boolean,
        default: true,
      },
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
      center_list: {
        type: Array,
        default: () => {
          return [];
        },
      },
      all_count: {},
      treeInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      dynamicPage: 1,
    },
    components: {
      SCharacterCard,
    },
    watch: {
      children: {
        handler(newValue, oldValue) {
          if (!!newValue && newValue != {} && newValue.length > 0) {
            let arr = newValue;
            if (!!arr[0] && !!arr[0].id) {
              for (let i = 0; i < arr.length; i++) {
                arr[i].isHave = !!arr[i].spouse_val && arr[i].spouse_val.length == 0;
                for (let j = 0; j < arr[i].children.length; j++) {
                  for (let k = 0; k < arr[i].spouse_val.length; k++) {
                    if (arr[i].spouse_val[k].id == arr[i].children[j].mq_id) {
                      arr[i].spouse_val[k].mq_flag = true;
                    }
                  }
                }
              }
              // arr.forEach(item => {
              //   setTimeout(()=>{
              //     this.generationList.push(item);
              //   },100)
              // });
              this.generationList = arr;
            } else {
              this.generationList = [];
              uni.hideLoading();
              this.$nextTick(() => {
                this.$refs.addChild.getPosition();
              });
            }
          }
          // 添加成员接受参数
          this.generationList.forEach((item, index) => {
            uni.$off(`appendMember_${item.id}`);
            uni.$off(`appendMemberWife_${item.id}`);
            uni.$on(`appendMember_${item.id}`, (obj) => {
              this.is_listen = true;
              console.log(item.id, obj.z_parent_id, item.id == Number(obj.z_parent_id));
              if (item.id == Number(obj.z_parent_id)) {
                console.log('已找到主从', item, this.genealogicalRanking == item.shi);
                if (this.treeInfo.top_list.shi_count == item.shi) {
                  if (item.has_children == 1) {
                    // #ifdef H5
                    window.open(`${window.location.href.split('#')[0]}#/pages/genealogy/management?id=${this.options.id}&name=${this.options.name}-${item.surname + item.name}节点&add_time=${this.options.add_time}&username=${this.options.username}&is_firstScreen=true&member_id=${item.id}&is_confirm=true&dynamicPage=${this.dynamicPage + 1}`);
                    // #endif
                    // #ifndef H5
                    this.phoneJump(item);
                    // #endif
                  } else {
                    if (!!item.spouse_val && item.spouse_val.length > 1) {
                      for (let l = 0; l < item.spouse_val.length; l++) {
                        if (item.spouse_val[l].id == obj.f_parent_id) {
                          console.log('已找到副从', item.spouse_val[l]);
                          this.generationList[index].spouse_val[l].children.push(obj);
                          this.addGeneration(obj);
                          uni.$emit(`changeWidth${this.dynamicPage}`);
                        }
                      }
                    } else {
                      this.generationList[index].children.push(obj);
                      this.addGeneration(obj);
                      uni.$emit(`changeWidth${this.dynamicPage}`);
                    }
                  }
                } else {
                  if (!!item.spouse_val && item.spouse_val.length > 1) {
                    for (let l = 0; l < item.spouse_val.length; l++) {
                      if (item.spouse_val[l].id == obj.f_parent_id) {
                        console.log('已找到副从', item.spouse_val[l]);
                        this.generationList[index].spouse_val[l].children.push(obj);
                        this.addGeneration(obj);
                        uni.$emit(`changeWidth${this.dynamicPage}`);
                      }
                    }
                  } else {
                    this.generationList[index].children.push(obj);
                    this.addGeneration(obj);
                    uni.$emit(`changeWidth${this.dynamicPage}`);
                  }
                }
              }
            });
            uni.$on(`appendMemberWife_${item.id}`, async (obj) => {
              console.log('添加成员', obj);
              this.is_listen = true;
              console.log(item.id, obj.z_parent_id, item.id == Number(obj.z_parent_id));
              if (item.id == Number(obj.z_parent_id)) {
                console.log('已找到主从', item);
                if (!!item.spouse_val && item.spouse_val.length == 1) {
                  this.generationList[index].spouse_val[0].children = this.generationList[index].children;
                  this.generationList[index].children = [];
                }
                this.generationList[index].spouse_val.push(obj);
                await uni.$emit(`changeWidth${this.dynamicPage}`);
              }
            });
          });
        },
        immediate: true,
        deep: true,
      },
    },
    computed: {
      sheep() {
        return sheep;
      },
    },
    mounted() {
      uni.$on('unload', () => {
        // uni.$off(`generationChange${this.dynamicPage}`);
        uni.$off('unload');
      });
      this.$nextTick(() => {
        if (!!this.isTopLevel) {
          uni.$on(`generationChange${this.dynamicPage}`, () => {
            this.getPosition(0);
          });
        }
      });
      // 更新世的高度
      uni.$on(`renewal_${this.dynamicPage}`, () => {
        this.getPosition();
      });
    },
    methods: {
      openAddPersonnelPopup(info) {
        this.$emit('openAddPersonnelPopup', info);
      },
      clickAdd() {
        this.$emit('clickAdd');
      },
      getPosition(id) {
        const query = uni.createSelectorQuery().in(this);
        query.select(`#generation`).boundingClientRect((rect) => {
          this.rectHeight = rect.height;
          this.$emit('transmitCoordinate', rect);
        }).exec();
      },
      // 手机模式下的跳转页面
      phoneJump(item) {
        sheep.$router.go('/pages/genealogy/management', {
          id: this.options.id,
          name: `${this.options.name}-${item.surname + item.name}节点`,
          add_time: this.options.add_time,
          username: this.options.username,
          is_firstScreen: true,
          member_id: item.id,
          dynamicPage: this.dynamicPage + 1,
        });
      },
      // 删除节点
      delete_card(obj) {
        if (!!obj.is_spouse) {
          let index = this.generationList.findIndex(item => item.id == obj.id);
          let index1 = this.generationList[index].spouse_val.findIndex(item => item.id == obj.spouseId);
          this.deleteGeneration(this.generationList[index].spouse_val[index1]);
          this.generationList[index].spouse_val.splice(index1, 1);
        } else {
          let index = this.generationList.findIndex(item => item.id == obj.id);
          this.deleteGeneration(this.generationList[index]);
          this.generationList.splice(index, 1);
        }
      },
      // 添加世的操作
      addGeneration(obj) {
        let shi = {};
        for (const shiKey in this.treeInfo.currentShi) {
          if (obj.shi_cn == this.treeInfo.currentShi[shiKey].shi_cn) {
            shi = this.treeInfo.currentShi[shiKey];
          }
        }
        if (JSON.stringify(shi) == '{}') {
          this.treeInfo.currentShi.push({
            generation: obj.generation,
            shi: obj.shi,
            shi_cn: obj.shi_cn,
          });
        }
      },
      // 删除世的操作
      deleteGeneration(obj) {
        let shi = '';
        for (const shiKey in this.treeInfo.currentShi) {
          if (obj.shi_cn == this.treeInfo.currentShi[shiKey].shi_cn) {
            shi = shiKey;
          }
        }
        if (shi != '') {
          delete this.treeInfo.currentShi[shi];
        }
      },
    },
  };
</script>

<template>
  <view id="generation" class="flex" style="position: relative;"
        :style="{
      background:showBackground ? '#F5F5F5' : 'transparent'
    }"
  >
    <view class="flex flex-column align-center justify-around wh_200 flex-sub"
          v-if="generationList.length > 0 && rectHeight != 0"
    >
      <view class="hW_80 fs_26 fw_500 color_4B4B4B flex align-center justify-center generationIdentification"
            v-for="(item,index) in treeInfo.currentShi"
            :key="index">
        <view class="wh_26">{{ item.shi_cn }}</view>
        <view class="ml_10 wh_26" style="writing-mode: vertical-rl;white-space: nowrap">
          ︻{{ item.generation || '辈' }}︼
        </view>
      </view>
    </view>
    <template v-if="generationList.length > 0">
      <view v-for="(item, index) in generationList"
            :id="`generationList${index}`"
            :key="index"
            class="flex flex-column align-center"
            style="position: relative"
      >
        <view v-if="!isTopLevel && generationList.length > 1"
              class="top"
              :class="{
                first: index == 0,
                last:index == generationList.length - 1
              }"
              :style="{
                width: index == 0 && !!item.isHave ? '50%' : index == generationList.length - 1 && (!!item.isHave ||  item.children.length > 1) ? (item.children.length > 1 && item.spouse_val.length > 0 ? `50%` : '50%') : index == generationList.length - 1 && (!!item.children ||  item.children.length <= 1) ?  (item.spouse_val.length > 0 ? `50%` : '29%') : index == 0 ? '50%' : index == generationList.length - 1 ? '50%' : '100%',
              }"
        ></view>
        <!-- 这里渲染每个子项的数据 -->
        <s-character-card :isOwnFlag="false"
                          :info="item"
                          :isTopLevel="isTopLevel"
                          :index="index"
                          :is_create="is_create"
                          :is_init="is_init"
                          :length="generationList.length"
                          :generation="generation"
                          :centerId="centerId"
                          :endId="endId"
                          @addMember="openAddPersonnelPopup"
                          @openAddPersonnelPopup="openAddPersonnelPopup"
                          :id="item.id"
                          :genealogicalHead="genealogicalHead"
                          :listWidth="listWidth"
                          :genealogicalRanking="1"
                          :zibei_List="zibei_List"
                          :is_simple="is_simple"
                          :show_die_gray="show_die_gray"
                          :is_first="is_first"
                          :options="options"
                          :center_list="center_list"
                          :treeInfo="treeInfo"
                          :dynamicPage="dynamicPage"
                          @delete_card="delete_card"
        ></s-character-card>
        <!-- 递归调用自身来渲染子项的子项 -->
        <s-recursive-list :children="item.children" v-if="!!item.children && item.children.length > 0"
                          style="margin-top: 10rpx;" :is_create="is_create" :is_init="is_init"
                          :generation="generation + 1"
                          :is_simple="is_simple"
                          :id="item.id"
                          :genealogicalRanking="2"
                          :centerId="centerId"
                          :endId="endId"
                          :genealogicalHead="genealogicalHead"
                          :zibei_List="zibei_List"
                          :show_die_gray="show_die_gray"
                          :is_first="is_first"
                          :options="options"
                          :center_list="center_list"
                          :treeInfo="treeInfo"
                          :dynamicPage="dynamicPage"
                          @openAddPersonnelPopup="openAddPersonnelPopup"
        />
      </view>
    </template>
    <template v-else>
      <s-add ref="addChild" id="add" :dynamicPage="dynamicPage" @clickAdd="clickAdd"></s-add>
    </template>
    <view class="flex flex-column align-center justify-around wh_200"
          v-if="generationList.length > 0 && rectHeight != 0"
    >
      <view class="hW_80 fs_26 fw_500 color_4B4B4B flex align-center justify-center"
            v-for="(item,index) in treeInfo.currentShi"
            :key="index">
        <view class="ml_10 wh_26" style="writing-mode: vertical-rl;white-space: nowrap">
          ︻{{ item.generation || '辈' }}︼
        </view>
        <view class="wh_26">{{ item.shi_cn }}</view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
  .label {
    width: 117rpx;
    height: 220rpx;
    background: #6EA0FC;
    border-radius: 15rpx 15rpx 15rpx 15rpx;

    .text {
      width: 60rpx;
      height: 42rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 30rpx;
      color: #FFFFFF;
    }
  }

  .first {
    right: -1rpx;
  }

  .last {
    left: -1rpx;
  }

  .top {
    position: absolute;
    height: 2rpx;
    background: #707070;
  }

  .generationIdentification {

  }
</style>